﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UnityScriptEngine;
using System.Drawing.Printing;

namespace MBBHotelReservation
{
    public partial class frmTransactionsManager : Form
    {
        UnityProcessor proc = new UnityProcessor();
        Threader t = new Threader();
        UnityScript[] dat = new UnityScript[0];

        bool createNew = true;
        bool addServices = false;
        public string transactionNumber = "";
        public bool isViewing = false;

        public frmTransactionsManager()
        {
            InitializeComponent();
            InitializeFrameSliderForm();
        }
        
        private void InitializeForm()
        {
            //Process Events
            TransWindowEvents();
            MainWindowEvents();
            UnityEvents();

            //Control initial states
            txtTransactionDate.Value = DateTime.Now;
            txtServiceDate.Value = DateTime.Now;
            txtPackageDate.Value = DateTime.Now;
            txtPaymentDate.Value = DateTime.Now;
            chkServiceTime.Checked = false;
            chkPackageTime.Checked = false;
            //chkPaymentTime.Checked = false;
            txtServiceTime.Enabled = false;
            txtPackageTime.Enabled = false;
            //txtPaymentTime.Enabled = false;

            RoundOffTime();
            txtServiceTime.Value = DateTime.Parse(string.Format("{0}:{1}:{2}", curTime.Hours, curTime.Minutes, curTime.Seconds));
            txtPackageTime.Value = DateTime.Parse(string.Format("{0}:{1}:{2}", curTime.Hours, curTime.Minutes, curTime.Seconds));
            //txtPaymentTime.Value = DateTime.Parse(string.Format("{0}:{1}:{2}", curTime.Hours, curTime.Minutes, curTime.Seconds));

            //Brute force to hide unfinished implementations ^_^ cheers!
            //tabTransactions.TabPages.RemoveAt(1);
            tabTransactions.TabPages.RemoveAt(1);

            if (isViewing)
            {
                addServices = true;
                createNew = false;
                grpTransaction.Visible = true;
                btnPrint.Enabled = true;
                LoadTransactionData(transactionNumber);
            }
        }


        #region Transaction Window
        //Data Structure
        public struct TransactionItemDetailType
        {
            public bool isNew;
            public string dbKey;
            public string KeyID;
            public string StringData;
            public DateTime DateTimeData;
            public float NumericData;
        }
        public struct TransactionItemType
        {
            public bool isNew;
            public string TransNumber;
            public string RegNumber;
            public string RefNum;
            public string RegType;
            public float RegPrice;
            public DateTime RegDateTime;
            public string Remarks;
            public List<TransactionItemDetailType> Details;
        }
        //Subsystem attributes
        TimeSpan curTime = DateTime.Now.TimeOfDay;
        string TransNum = "", RegNum = "";
        List<string> autoName = new List<string>();
        List<string> autoRef = new List<string>();
        List<string> lstcats = new List<string>();
        List<string> amCats = new List<string>();
        //Data attribute
        List<TransactionItemType> TransData = new List<TransactionItemType>();
        TransactionItemType curTransData;
        //TransactionItemType loadTransData;
        private void TransState(bool s)
        {
            grpTransaction.Enabled = s;
            if (createNew)
                btnSave.Enabled = s;
            else
                btnSave.Enabled = !s;
        }
        private void TransWindowEvents()
        {
            //Checkboxes
            chkServiceTime.CheckedChanged += new EventHandler(delegate
            {
                RoundOffTime();
                txtServiceTime.Enabled = chkServiceTime.Checked;
                txtServiceTime.Value = DateTime.Parse(string.Format("{0}:{1}:{2}", curTime.Hours, curTime.Minutes, curTime.Seconds));
            });
            chkPackageTime.CheckedChanged += new EventHandler(delegate
            {
                RoundOffTime();
                txtPackageTime.Enabled = chkPackageTime.Checked;
                txtPackageTime.Value = DateTime.Parse(string.Format("{0}:{1}:{2}", curTime.Hours, curTime.Minutes, curTime.Seconds));
            });
            /*
            chkPaymentTime.CheckedChanged += new EventHandler(delegate
            {
                RoundOffTime();
                txtPaymentTime.Enabled = chkPaymentTime.Checked;
                txtPaymentTime.Value = DateTime.Parse(string.Format("{0}:{1}:{2}", curTime.Hours, curTime.Minutes, curTime.Seconds));
            });*/
            lstPayments.SelectedIndexChanged += new EventHandler(delegate
            {
                if (lstPayments.Text.Equals("CASH"))
                {
                    btnPaymentDetails.Enabled = false;
                }
                else
                {
                    btnPaymentDetails.Enabled = true;
                }
            });
            txtCustName.TextChanged += new EventHandler(delegate(object sender, EventArgs e)
            {
                if (!addServices)
                {
                    int ind = autoName.IndexOf(txtCustName.Text);
                    if (ind > -1)
                    {
                        txtRefNum.Text = autoRef[ind];
                        txtCustName.ForeColor = Color.Black;

                    }
                    else
                    {
                        txtRefNum.Text = "Invalid Customer Profile!";
                        txtCustName.ForeColor = Color.Red;
                    }
                }
            });
            btnServiceDetails.Click += new EventHandler(delegate
            {
                if (lstServices.Text == "")
                {
                    MessageBox.Show("Please select a service first.", "Service Details",
                        MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }
                frmServiceDetails frmsvcdet = new frmServiceDetails();
                if (!lstServices.Text.Equals("AMENITIES"))
                {
                    frmsvcdet.SetLists(lstcats.ToArray(), txtServiceDate.Value.ToString("yyyy-MM-dd"), lstServices.Text, txtTransNum.Text);
                }
                else
                {
                    frmsvcdet.SetLists(amCats.ToArray(), txtServiceDate.Value.ToString("yyyy-MM-dd"), lstServices.Text, txtTransNum.Text);
                }
                if(curTransData.Details != null)frmsvcdet.Details = curTransData.Details;
                DialogResult svcdetdlg = frmsvcdet.ShowDialog();
                if (svcdetdlg == System.Windows.Forms.DialogResult.OK)
                {
                    curTransData.Details = new List<TransactionItemDetailType>();
                    curTransData.Details = frmsvcdet.Details;
                    btnServiceDetails.Text = curTransData.Details[1].StringData;
                    txtServicePrice.Value = (decimal)curTransData.Details[2].NumericData;
                }
            });
            btnAddService.Click += new EventHandler(delegate
            {
                if (lstServices.Text == "")
                {
                    MessageBox.Show("Please select a service first.", "Service Details",
                        MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    return;
                }
                DialogResult dlg = MessageBox.Show("Please double check your entries before Adding Service.\r\n" +
                "Do you wish to continue adding?", "Add Service", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlg == System.Windows.Forms.DialogResult.No) return;

                curTransData.TransNumber = txtTransNum.Text;
                curTransData.RefNum = txtRefNum.Text;
                curTransData.RegNumber = txtRegNum_1.Text;
                curTransData.RegType = lstServices.Text;
                curTransData.RegPrice = (float)txtServicePrice.Value;
                if (chkServiceTime.Checked)
                {
                    curTransData.RegDateTime = DateTime.Parse(txtServiceDate.Value.ToString("yyyy-MM-dd") + " " + txtServiceTime.Value.ToString("HH:mm:ss"));
                }
                else
                {
                    curTransData.RegDateTime = DateTime.Parse(txtServiceDate.Value.ToString("yyyy-MM-dd"));
                }
                
                TransData.Add(curTransData);
                //save services
                SaveServices();
            });
            btnPaymentDetails.Click += new EventHandler(delegate
            {
                frmPaymentDetails frmpaydet = new frmPaymentDetails();
                DialogResult paydetdlg = frmpaydet.ShowDialog();
                if (paydetdlg == System.Windows.Forms.DialogResult.OK)
                {
                    //Include Bank, Account Name, Account Number, IssueDate, DueDate
                    lstDetails.Items.Clear();
                    if (frmpaydet.TextDetails[0] != "") lstDetails.Items.Add(frmpaydet.TextDetails[0]);
                    if (frmpaydet.TextDetails[1] != "") lstDetails.Items.Add(frmpaydet.TextDetails[1]);
                    if (frmpaydet.TextDetails[2] != "") lstDetails.Items.Add(frmpaydet.TextDetails[2]);
                    if (frmpaydet.DateDetails[0].ToString("yyyy-MM-dd") != "1200-01-01") lstDetails.Items.Add(frmpaydet.DateDetails[0].ToString("yyyy-MM-dd"));
                    if (frmpaydet.DateDetails[1].ToString("yyyy-MM-dd") != "1200-01-01") lstDetails.Items.Add(frmpaydet.DateDetails[1].ToString("yyyy-MM-dd"));

                    if (frmpaydet.Amount > -1)
                    {
                        txtPaymentAmount.Value = (decimal)frmpaydet.Amount;
                        lstDetails.Items.Add((decimal)frmpaydet.Amount);
                    }
                }
            });
            btnCancelService.Click += new EventHandler(delegate
            {
                DialogResult dlg = MessageBox.Show("Please double check the chosen item from the list before cancelling.\r\n" +
                "Do you wish to cancel reservation or check in?", "Service Cancellation", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlg == System.Windows.Forms.DialogResult.No) return;

                string fData = lstRegs.SelectedItems[0].ToString();
                string[] fArr;
                fArr = fData.Split(',');
                string fType = fArr[1];
                string fRoom = fArr[2];

                if (fType.Equals("CHECKIN") || fType.Equals("RESERVATION"))
                {
                    CancelService(fType, fRoom);
                }
                else
                {
                    MessageBox.Show("Cancellation on this item is invalid...");
                    return;
                }

            });
            
            btnCancel.Click += new EventHandler(delegate
            {
                TransResetFields();
                LoadTransactionList();
                //additional code
                MainState(true);
                txtCustName.ReadOnly = false;
                txtTransactionDate.Enabled = true;
                grpTransaction.Visible = false;
                btnAdd.Enabled = true;
                addServices = false;
                createNew = false;
            });
            btnSave.Click += new EventHandler(delegate
            {
                CreateTransaction();
            });
            chkDiscountPercent.CheckedChanged += new EventHandler(delegate
            {
                txtDiscountPercent.Enabled = chkDiscountPercent.Checked;
                if(chkDiscountPercent.Checked) chkDiscountAmt.Checked = false;
            });
            chkDiscountAmt.CheckedChanged += new EventHandler(delegate
            {
                txtDiscountAmt.Enabled = chkDiscountAmt.Checked;
                if(chkDiscountAmt.Checked)chkDiscountPercent.Checked = false;
            });
            btnAddDiscount.Click += new EventHandler(delegate
            {
                if (!chkDiscountAmt.Checked && !chkDiscountPercent.Checked) return;
                if (chkDiscountAmt.Checked && txtDiscountAmt.Value == 0m) return;
                DialogResult dlg = MessageBox.Show("Please double check your entries before Adding Discounts.\r\n" +
                "Do you wish to continue adding?", "Add Discount", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlg == System.Windows.Forms.DialogResult.No) return;
                
                AddDiscount();
            });
            //PAYMENT
            btnAddPayment.Click += new EventHandler(delegate
            {
                DialogResult dlg = MessageBox.Show("Please double check your entries before Adding Payments.\r\n" +
                "Do you wish to continue adding?", "Add Payment", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlg == System.Windows.Forms.DialogResult.No) return;

                if ((!lstPayments.Text.Equals("")) && txtOR.Text != "")
                {
                    if (!lstPayments.Text.Equals("CASH"))
                    {
                        if (lstDetails.Items.Count == 6)
                        {
                            
                                AddPayment();
                        }
                        else
                        {
                            MessageBox.Show("Please Check Your Payment Information");
                        }
                    }
                    else
                    {
                        AddPayment();
                    }
                }
            });
        }
        private void TransResetFields()
        {
            foreach (Control ctl in grpTransaction.Controls)
            {
                if (ctl is TextBox) ((TextBox)ctl).Text = "";
            }
            foreach (Control ctl in tabServices.Controls)
            {
                if (ctl is TextBox) ((TextBox)ctl).Text = "";
                if (ctl is NumericUpDown) ((NumericUpDown)ctl).Value = ((NumericUpDown)ctl).Minimum;
                if (ctl is ComboBox) ((ComboBox)ctl).Items.Clear();
                if (ctl is CheckBox) ((CheckBox)ctl).Checked = false;
            }
            foreach (Control ctl in tabPackages.Controls)
            {
                if (ctl is TextBox) ((TextBox)ctl).Text = "";
                if (ctl is NumericUpDown) ((NumericUpDown)ctl).Value = ((NumericUpDown)ctl).Minimum;
                if (ctl is ComboBox) ((ComboBox)ctl).Items.Clear();
                if (ctl is CheckBox) ((CheckBox)ctl).Checked = false;
            }
            foreach (Control ctl in tabPayments.Controls)
            {
                if (ctl is TextBox) ((TextBox)ctl).Text = "";
                if (ctl is NumericUpDown) ((NumericUpDown)ctl).Value = ((NumericUpDown)ctl).Minimum;
                if (ctl is ComboBox) ((ComboBox)ctl).Items.Clear();
                if (ctl is CheckBox) ((CheckBox)ctl).Checked = false;
            }
            foreach (Control ctl in tabDiscount.Controls)
            {
                if (ctl is TextBox) ((TextBox)ctl).Text = "";
                if (ctl is NumericUpDown) ((NumericUpDown)ctl).Value = ((NumericUpDown)ctl).Minimum;
                if (ctl is ComboBox) ((ComboBox)ctl).Items.Clear();
                if (ctl is CheckBox) ((CheckBox)ctl).Checked = false;
            }
        }
        private void InitTransactionWindow(bool isload)
        {
            TransState(false);

            if (isload) TransData = new List<TransactionItemType>();
            curTransData = new TransactionItemType();
            curTransData.isNew = true;
            UnityScript u = new UnityScript("LOADDETAILS", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fCurNum, fStamp FROM tblgenerate WHERE fID='3'");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fCurNum, fStamp FROM tblgenerate WHERE fID='2'");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fData, fStamp FROM tbllookup WHERE fKey='SERVICE TYPE' ORDER BY fData ASC");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fPackageName, fStamp FROM tblpackageitems ORDER BY fPackageName ASC");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fData, fStamp FROM tbllookup WHERE fKey='PAYMENT TYPE' ORDER BY fData ASC");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fRefNum, fName, fStamp FROM tblprofile");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fData, fStamp FROM tbllookup WHERE fKey='SERVICE DETAIL CATEGORY' ORDER BY fData ASC");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fData, fStamp FROM tbllookup WHERE fKey='DISCOUNT_MSG' ORDER BY fData ASC");
            //added for the category of amenities
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fData, fStamp FROM tbllookup WHERE fKey='AMENITIES' ORDER BY fData ASC");
            if (createNew)
            {
                tabTransactions.Visible = false;
            }
            else
            {
                tabTransactions.Visible = true;
                btnSave.Enabled = false;
                btnAdd.Enabled = false;
            }

            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        private void CreateTransaction()
        {
            TransState(false);
            UnityScript u = new UnityScript("CREATETRANS", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_INSERT, "tbltransactions(fNumber, fRefNum, fDate, fStatus)",
                new string[]{
                    TransNum,
                    txtRefNum.Text,
                    txtTransactionDate.Value.ToString("yyyy-MM-dd"),
                    "ACTIVE"
                });
            u.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET fCurNum = fCurNum + 1", "(fID='3')");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        private void ParseLoadedData()
        {

        }
        private void SaveServices()
        {
            UnityScript u = new UnityScript("SAVETRANSACTIONITEMS", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_INSERT, "tbltransactionitems(fTransNum, fRegNum, fRefNum, fType, fPrice, fDateTime, fRemarks)",
                new string[]{
                    curTransData.TransNumber,
                    curTransData.RegNumber,
                    curTransData.RefNum,
                    curTransData.RegType,
                    curTransData.RegPrice.ToString(),
                    curTransData.RegDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    curTransData.Remarks
                });
            u.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET fCurNum = fCurNum + 1", "(fID='2')");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fCurNum, fStamp FROM tblgenerate WHERE fID='2'");

            //MONITORING
            if (curTransData.RegType.Equals("CHECKIN"))
            {
                
                u.Script_Add(Script.DBPUX_INSERT, "tblmonitoring(fTransNum, fDate, fRegNum, fRoom, fCheckInDateTime, fTransactionMode)",
                    new string[]{
                    curTransData.TransNumber,
                    curTransData.RegDateTime.ToString("yyyy-MM-dd"),
                    curTransData.RegNumber,
                    curTransData.Details[1].StringData,
                    curTransData.RegDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    "Occupied"
                });
                
            }
            else if (curTransData.RegType.Equals("CHECKOUT"))
            {
                u.Script_Add(Script.DBPUX_UPDATE, "tblmonitoring SET fCheckOutDateTime = '"+curTransData.RegDateTime.ToString("yyyy-MM-dd HH:mm:ss")+"'", "(fTransactionMode = 'Occupied') AND fRoom = '"
                    + curTransData.Details[1].StringData+"' ");
                   
            }
            else if (curTransData.RegType.Equals("ACTUALCHECKOUT"))
            {
                u.Script_Add(Script.DBPUX_UPDATE, "tblmonitoring SET fTransactionMode = 'HouseKeeping', fCheckOutDateTime = '" + curTransData.RegDateTime.ToString("yyyy-MM-dd HH:mm:ss") + "'", "(fTransactionMode = 'Occupied') AND fRoom = '"
                    + curTransData.Details[1].StringData + "' ");

            }
            else if (curTransData.RegType.Equals("RESERVATION"))
            {

                u.Script_Add(Script.DBPUX_INSERT, "tblmonitoring(fTransNum, fDate, fRegNum, fRoom, fCheckInDateTime, fTransactionMode)",
                    new string[]{
                    curTransData.TransNumber,
                    curTransData.RegDateTime.ToString("yyyy-MM-dd"),
                    curTransData.RegNumber,
                    curTransData.Details[1].StringData,
                    //Debug Note: Changed 'Reserved'to 'Reserve'
                    //XCoder
                    curTransData.RegDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    "Reserve"
                });
            }
            
            u.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                    new string[]{
                        curTransData.RegNumber,
                        curTransData.Details[0].KeyID,
                        curTransData.Details[0].StringData
                    });
            
            
            u.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                    new string[]{
                        curTransData.RegNumber,
                        curTransData.Details[1].KeyID,
                        curTransData.Details[1].StringData
                    });

            u.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fNumericData)",
                    new string[]{
                        curTransData.RegNumber,
                        curTransData.Details[2].KeyID,
                        curTransData.Details[2].NumericData.ToString()
                    });

            for (int i = 3; i < curTransData.Details.Count; i++)
            {
                if (i == 3 ||  i == 6 || i == 7 || i == 15 || i == 16)
                {
                    u.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fDateTimeData)",
                        new string[]{
                        curTransData.RegNumber,
                        curTransData.Details[i].KeyID,
                        curTransData.Details[i].DateTimeData.ToString("yyyy-MM-dd HH:mm:ss")
                    });
                }
                else
                {
                    u.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                        new string[]{
                        curTransData.RegNumber,
                        curTransData.Details[i].KeyID,
                        curTransData.Details[i].StringData
                    });
                }
            }
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        private void AddDiscount()
        {
            curTransData.TransNumber = txtTransNum.Text;
            curTransData.RefNum = txtRefNum.Text;
            curTransData.RegNumber = txtRegNum_4.Text;
            curTransData.RegDateTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
            if (chkDiscountPercent.Checked)
            {
                curTransData.RegType = "DISCOUNT_PERCENT";
                curTransData.RegPrice = (float)txtDiscountPercent.Value;
            }
            else if(chkDiscountAmt.Checked)
            {
                curTransData.RegType = "DISCOUNT_AMOUNT";
                curTransData.RegPrice = (float)txtDiscountAmt.Value;
            }
            curTransData.Details = new List<TransactionItemDetailType>();
            curTransData.Details.Add(new TransactionItemDetailType
            {
                KeyID = "NOTES",
                StringData = txtNotes.Text
            });
            TransData.Add(curTransData);
            //Database
            UnityScript u = new UnityScript("SAVETRANSACTIONITEMS", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_INSERT, "tbltransactionitems(fTransNum, fRegNum, fRefNum, fType, fPrice, fDateTime, fRemarks)",
                new string[]{
                    curTransData.TransNumber,
                    curTransData.RegNumber,
                    curTransData.RefNum,
                    curTransData.RegType,
                    curTransData.RegPrice.ToString(),
                    curTransData.RegDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    curTransData.Remarks
                });
            u.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET fCurNum = fCurNum + 1", "(fID='2')");
            u.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fCurNum, fStamp FROM tblgenerate WHERE fID='2'");
            u.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                    new string[]{
                        curTransData.RegNumber,
                        curTransData.Details[0].KeyID,
                        curTransData.Details[0].StringData
                    });
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        private void CancelService(string fType, string fRoom)
        {
            UnityScript u = new UnityScript("CANCELSERVICES", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_UPDATE, "tbltransactionItems SET fRemarks = 'Cancelled'", "fTransNum = '" + txtTransNum.Text + "' AND fType = '"+fType+"'");
            //Debug Note: Changed 'Reserved'to 'Reserve'
            //XCoder
            u.Script_Add(Script.DBPUX_UPDATE, "tblmonitoring SET fTransactionMode = 'Cleared'", "(fTransactionMode = 'Reserve' OR fTransactionMode = 'Occupied') AND fRoom = '"
                    + fRoom + "' AND fTransNum = '"+txtTransNum.Text+"'");
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        //payment details
        private void AddPayment()
        {
            curTransData.TransNumber = txtTransNum.Text;
            curTransData.RefNum = txtRefNum.Text;
            curTransData.RegNumber = txtRegNum_3.Text;
            curTransData.RegDateTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd"));
            curTransData.RegType = "PAYMENT";
            curTransData.RegPrice = (float)txtPaymentAmount.Value;

            UnityScript x = new UnityScript("SAVETRANSACTIONITEMS", 2);
            x.Script_Add(Script.DBPUX_BEGIN);
            x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitems(fTransNum, fRegNum, fRefNum, fType, fPrice, fDateTime, fRemarks)",
                new string[]{
                    curTransData.TransNumber,
                    curTransData.RegNumber,
                    curTransData.RefNum,
                    curTransData.RegType,
                    curTransData.RegPrice.ToString(),
                    curTransData.RegDateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    curTransData.Remarks
                });
            x.Script_Add(Script.DBPUX_UPDATE, "tblgenerate SET fCurNum = fCurNum + 1", "(fID='2')");
            x.Script_Add(Script.DBPUX_QUERY, "SELECT fID, fCurNum, fStamp FROM tblgenerate WHERE fID='2'");

            TransactionItemDetailType[] buf = new TransactionItemDetailType[3 + lstDetails.Items.Count];
            buf[0].KeyID = "CATEGORY";
            buf[0].StringData = "PAYMENT";
            buf[1].KeyID = "TYPE";
            buf[1].StringData = lstPayments.Text;
            buf[2].KeyID = "AMOUNT";
            buf[2].NumericData = (float)txtPaymentAmount.Value;
            if (buf.Length > 3)
            {
                buf[3].KeyID = "BANK";
                buf[3].StringData = lstDetails.Items[0].ToString();

                buf[4].KeyID = "ACCOUNT_NAME";
                buf[4].StringData = lstDetails.Items[1].ToString();

                buf[5].KeyID = "ACCOUNT_NUMBER";
                buf[5].StringData = lstDetails.Items[2].ToString();

                buf[6].KeyID = "ISSUEDATE";
                buf[6].DateTimeData = DateTime.Parse(lstDetails.Items[3].ToString());

                buf[7].KeyID = "DUEDATE";
                buf[7].DateTimeData = DateTime.Parse(lstDetails.Items[4].ToString());

                buf[8].KeyID = "ORIG_AMOUNT";
                buf[8].NumericData = float.Parse(lstDetails.Items[5].ToString());
            }

            curTransData.Details = new List<TransactionItemDetailType>();
            curTransData.Details.Add(new TransactionItemDetailType
            {
                KeyID = "CATEGORY",
                StringData = "PAYMENT"
            });
            curTransData.Details.Add(new TransactionItemDetailType
            {
                KeyID = "TYPE",
                StringData = lstPayments.Text
            });
            TransData.Add(curTransData);
            
            if (lstPayments.Text.Equals("CASH"))
            {
                x.Script_Add(Script.DBPUX_INSERT, "tblpayments(fTransNum, fRegNum, fRefNum, fDate, fOfficialReceipt, fPaymentAmount, fType)",
                    new string[]{
                        curTransData.TransNumber,
                        curTransData.RegNumber,
                        curTransData.RefNum,
                        txtPaymentDate.Value.ToString("yyyy-MM-dd"),
                        txtOR.Text,
                        curTransData.RegPrice.ToString(),
                        lstPayments.Text
                    });


            }
            else
            {
                x.Script_Add(Script.DBPUX_INSERT, "tblpayments (fTransNum, fRegNum, fRefNum, fDate, fOfficialReceipt, fPaymentAmount, fType, fBank, fAccountName, fAccountNum, fAmount, fIssueDate, fDueDate)",
                    new string[]{
                        curTransData.TransNumber,
                        curTransData.RegNumber,
                        curTransData.RefNum,
                        txtPaymentDate.Value.ToString("yyyy-MM-dd"),
                        txtOR.Text,
                        curTransData.RegPrice.ToString(),
                        lstPayments.Text,
                        lstDetails.Items[0].ToString(),
                        lstDetails.Items[1].ToString(),
                        lstDetails.Items[2].ToString(),
                        lstDetails.Items[5].ToString(),
                        lstDetails.Items[3].ToString(),
                        lstDetails.Items[4].ToString()
                    });
            }

            x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                    new string[]{
                        curTransData.RegNumber,
                        buf[0].KeyID,
                        buf[0].StringData
                    });
            x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                    new string[]{
                        curTransData.RegNumber,
                        buf[1].KeyID,
                        buf[1].StringData
                    });

            x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fNumericData)",
                    new string[]{
                        curTransData.RegNumber,
                        buf[2].KeyID,
                        buf[2].NumericData.ToString()
                    });
            if (buf.Length > 3)
            {
                x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                    new string[]{
                        curTransData.RegNumber,
                        buf[3].KeyID,
                        buf[3].StringData
                    });
                x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                        new string[]{
                        curTransData.RegNumber,
                        buf[4].KeyID,
                        buf[4].StringData
                    });
                x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fStringData)",
                    new string[]{
                        curTransData.RegNumber,
                        buf[5].KeyID,
                        buf[5].StringData
                    });
                x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fDateTimeData)",
                        new string[]{
                        curTransData.RegNumber,
                        buf[6].KeyID,
                        buf[6].DateTimeData.ToString("yyyy-MM-dd")
                    });
                x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fDateTimeData)",
                    new string[]{
                        curTransData.RegNumber,
                        buf[7].KeyID,
                        buf[7].DateTimeData.ToString("yyyy-MM-dd")
                    });
                x.Script_Add(Script.DBPUX_INSERT, "tbltransactionitemdetails(fRegNum, fKeyID, fNumericData)",
                        new string[]{
                        curTransData.RegNumber,
                        buf[8].KeyID,
                        buf[8].NumericData.ToString()
                    });
            }
            x.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(x);
        }

        #endregion

        #region Main Window
        //Main Window
        private void MainWindowEvents()
        {
            //printing transaction
            btnPrint.Click += new EventHandler(delegate 
            {
                PrintTransactionForm();
            });
            
            btnAdd.Click += new EventHandler(delegate
            {
                //Load GUI data
                createNew = true;
                lstRegs.Items.Clear();
                grpTransaction.Visible = true;
                btnAdd.Enabled = false;
                btnPrint.Enabled = false;
                InitTransactionWindow(true);
            });
            grdItems.DoubleClick += new EventHandler(delegate
            {
                if (grdItems.SelectedRows.Count == 1)
                {
                    addServices = true;
                    createNew = false;
                    grpTransaction.Visible = true;
                    btnPrint.Enabled = true;
                    LoadTransactionData(grdItems.SelectedRows[0].Cells[0].Value.ToString());
                }
            });
            txtPage.ValueChanged += new EventHandler(delegate
            {
                LoadTransactionList();
            });
            txtSearch.KeyPress += new KeyPressEventHandler(delegate(object sender, KeyPressEventArgs e)
            {
                if (e.KeyChar == (char)13)
                {
                    prevSrc = txtSearch.Text;
                    txtPage.Value = 1;
                    LoadTransactionList();
                }
            });
            btnSearch.Click += new EventHandler(delegate
            {
                prevSrc = txtSearch.Text;
                txtPage.Value = 1;
                LoadTransactionList();
            });
            LoadTransactionList();
        }
        string prevSrc = "";
        private void LoadTransactionList()
        {
            MainState(false);
            UnityScript u = new UnityScript("LOADTRANSLIST", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, string.Format("SELECT fID, fNumber AS 'Transaction Number' , fName AS 'Client Name' , fDate AS 'Date', fStatus AS 'Status', fStamp FROM tbltransactions T1, " +
                "(SELECT fName, fRefNum FROM tblprofile) AS T2 WHERE (T1.fRefNum = T2.fRefNum) AND (" +
                "(fNumber LIKE '%{1}%') OR (T2.fName LIKE '%{1}%') OR (fDate LIKE '%{1}%') OR (fStatus LIKE '%{1}%') OR (T2.fRefNum LIKE '%{1}%')" +
                ")ORDER BY fNumber DESC LIMIT {0}, 50",
                (txtPage.Value - 1) * 50,
                prevSrc
                )
                );
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);

        }
        private void LoadTransactionData(string transNum)
        {
            MainState(false);
            
            UnityScript u = new UnityScript("LOADTRANSDATA", 2);
            u.Script_Add(Script.DBPUX_BEGIN);
            u.Script_Add(Script.DBPUX_QUERY, string.Format(
                "SELECT fID, fNumber, t1.fRefNum, fName AS 'ClientName', fDate, fStatus, fStamp FROM tbltransactions AS t1, "+
                "(SELECT fName, fRefNum FROM tblprofile) AS T2 WHERE (T1.fRefNum = T2.fRefNum) AND fNumber='{0}'", 
                transNum)
                );
            u.Script_Add(Script.DBPUX_QUERY, string.Format(
                "SELECT fID, fTransNum, fRegNum, fRefNum, fType, fPrice, fDateTime, fRemarks, fStamp FROM tbltransactionitems WHERE fTransNum='{0}'",
                transNum)
                );
            u.Script_Add(Script.DBPUX_QUERY, string.Format(
                "SELECT fID, fRegNum, fKeyID, fStringData, fDateTimeData, fNumericData, fStamp FROM tbltransactionitemdetails WHERE fRegNum IN "+
                "(SELECT fRegNum FROM tbltransactionitems WHERE fTransNum='{0}')",
                transNum)
                );
            u.Script_Add(Script.DBPUX_COMMIT);
            proc.Run(u);
        }
        private void MainState(bool state)
        {
            mainPanel.Enabled = state;
            grdItems.Enabled = state;
            btnAdd.Enabled = state;
        }

        //struct used by the printing module
        struct printModData
        {
            public string strDateTime;
            public string strRegType;
            public string strRegData;
            public float regPrice;
        }
        //Printing Module
        int i = 0;
        int pp = 1;
        printModData [] transactionInfo = new printModData[0];

        void PrintTransactionForm()
        {
            PrintDocument pd = new PrintDocument();
            pd.DocumentName = "Registration Form";
            pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
            PrintDialog pdlg = new PrintDialog();
            pdlg.Document = pd;
            // Set the page orientation to landscape.
            //pd.DefaultPageSettings.Landscape = true;
            //pd.DefaultPageSettings.PaperSize = new PaperSize("Folio", 850, 1300);
            //pd.DefaultPageSettings.PaperSize.Width = 1300;
            //pd.DefaultPageSettings.PaperSize.Height = 850;
            if (pdlg.ShowDialog() == DialogResult.OK)
            {
                PrintPreviewDialog ppdlg = new PrintPreviewDialog();
                pp = 1;
                i = 0;
                ppdlg.Document = pd;
                ppdlg.ShowDialog();
            }

        }
        void pd_PrintPage(object sender, PrintPageEventArgs e)
        {
            float lpp = 0;
            float y = 0;
            float tm = e.MarginBounds.Top;
            float lm = e.PageBounds.Left + 50;
            float lw = e.PageBounds.Width - 50;
            float th = e.PageBounds.Height - 100;
            float bm = e.PageBounds.Bottom - 100;
            float tHt = 0;
            float ht = 0;

            Font cFont;
            StringFormat sf = new StringFormat();
            //Title
            cFont = new Font("Arial", 16f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            y = 50;

            e.Graphics.DrawImage(pictureBox2.Image, 100, 35);
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString("Malolos Resort Club Royale ", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            cFont = new Font("Arial", 12f, FontStyle.Bold);
            y += tHt;
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("McArthur Highway, Mabolo, Malolos, Bulacan", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("Tel. No. (044) 791-03-78     Fax. No. (044) 796-01-31", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //SubTitle
            y += tHt;
            y += tHt;
            cFont = new Font("Arial", 13f, FontStyle.Bold);
            tHt = cFont.GetHeight(e.Graphics);
            e.Graphics.DrawString("Registration Form ", cFont, Brushes.Black, (lw + 100) / 2, y, sf);
            //Line
            y += tHt;
            y += tHt;
            e.Graphics.DrawLine(new Pen(Color.Black), new PointF(lm, y), new PointF(lw, y));

            //Guest Information
            sf.Alignment = StringAlignment.Near;
            y += tHt;
            //Transaction Date
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Transaction Date: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtTransactionDate.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            //Transaction Number
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Transaction Number: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString(""+txtTransNum.Text, cFont, Brushes.Black, lm + 240, y, sf);

            y += tHt;
            //Reference Number
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Reference Number: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtRefNum.Text, cFont, Brushes.Black, lm + 240, y, sf);

            
            y += tHt;
            //Guest or Corporate Name
            cFont = new Font("Arial", 11f, FontStyle.Regular);
            e.Graphics.DrawString("Guest / Corporate Name: ", cFont, Brushes.Black, lm + 5, y, sf);
            cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
            e.Graphics.DrawString("" + txtCustName.Text, cFont, Brushes.Black, lm + 240, y, sf);
           
            
            y += tHt;
            y += tHt;

            //Room Accomodation Details
            cFont = new Font("Arial", 11f, FontStyle.Bold);
            e.Graphics.DrawString("Room or Function Hall Details ", cFont, Brushes.Black, lm + 5, y, sf);

            for (int i = 0; i < transactionInfo.Length; i++)
            {
                if (transactionInfo[i].strRegType.Equals("CHECKIN"))
                {
                    y += tHt;
                    cFont = new Font("Arial", 11f, FontStyle.Regular);
                    e.Graphics.DrawString("Room Number ", cFont, Brushes.Black, lm + 5, y, sf);
                    cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
                    e.Graphics.DrawString("" + transactionInfo[i].strRegData, cFont, Brushes.Black, lm + 240, y, sf);
                    y += tHt;
                    cFont = new Font("Arial", 11f, FontStyle.Regular);
                    e.Graphics.DrawString("Check In Date and Time ", cFont, Brushes.Black, lm + 5, y, sf);
                    cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
                    e.Graphics.DrawString("" + transactionInfo[i].strDateTime , cFont, Brushes.Black, lm + 240, y, sf);
                }
                else if (transactionInfo[i].strRegType.Equals("CHECKOUT"))
                {
                   
                    y += tHt;
                    cFont = new Font("Arial", 11f, FontStyle.Regular);
                    e.Graphics.DrawString("Check Out Date and Time ", cFont, Brushes.Black, lm + 5, y, sf);
                    cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
                    e.Graphics.DrawString("" + transactionInfo[i].strDateTime + " : "+transactionInfo[i].strRegData, cFont, Brushes.Black, lm + 240, y, sf);
                }
                else if (transactionInfo[i].strRegType.Equals("RESERVATION"))
                {
                    y += tHt;
                    cFont = new Font("Arial", 11f, FontStyle.Regular);
                    e.Graphics.DrawString("Room Number ", cFont, Brushes.Black, lm + 5, y, sf);
                    cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
                    e.Graphics.DrawString("" + transactionInfo[i].strRegData, cFont, Brushes.Black, lm + 240, y, sf);
                    y += tHt;
                    cFont = new Font("Arial", 11f, FontStyle.Regular);
                    e.Graphics.DrawString("Check In Date and Time ", cFont, Brushes.Black, lm + 5, y, sf);
                    cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
                    e.Graphics.DrawString("" + transactionInfo[i].strDateTime, cFont, Brushes.Black, lm + 240, y, sf);
                }

            }
            /*
           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           e.Graphics.DrawString("Room Number ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           e.Graphics.DrawString("" + txtRoomNumber.Text, cFont, Brushes.Black, lm + 240, y, sf);

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           e.Graphics.DrawString("Time of the day ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           e.Graphics.DrawString("" + timeofDay, cFont, Brushes.Black, lm + 240, y, sf);

           

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           e.Graphics.DrawString("Check Out Date and Time ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           e.Graphics.DrawString("" + checkOutDateTime.Value, cFont, Brushes.Black, lm + 240, y, sf);

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           e.Graphics.DrawString("Number of Days: ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           e.Graphics.DrawString("" + txtNDays.Text, cFont, Brushes.Black, lm + 240, y, sf);

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           e.Graphics.DrawString("Number of Person: ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           e.Graphics.DrawString("" + txtNPerson.Text, cFont, Brushes.Black, lm + 240, y, sf);

           y += tHt;
           y += tHt;

           //Occupants List

           cFont = new Font("Arial", 11f, FontStyle.Underline);
           e.Graphics.DrawString("Occupant's Name ", cFont, Brushes.Black, lm + 5, y, sf);

           //Complimentary Breakfast

           cFont = new Font("Arial", 11f, FontStyle.Underline);
           e.Graphics.DrawString("Complementary Breakfast ", cFont, Brushes.Black, lm + 400, y, sf);

           //Occupants List and Breakfast
           for (int i = 0; i < grdItems.Rows.Count; i++)
           {
               y += tHt;
               cFont = new Font("Arial", 11f, FontStyle.Regular);
               e.Graphics.DrawString((i + 1) + ".  " + grdItems.Rows[i].Cells[0].Value.ToString(), cFont, Brushes.Black, lm + 5, y, sf);

               e.Graphics.DrawString((i + 1) + ".  " + grdItems.Rows[i].Cells[0].Value.ToString(), cFont, Brushes.Black, lm + 400, y, sf);
           }

           y += tHt;
           y += tHt;


           //Swimming Entrance

           cFont = new Font("Arial", 11f, FontStyle.Bold);
           e.Graphics.DrawString("Swimming Entrance ", cFont, Brushes.Black, lm + 5, y, sf);

           y += tHt;
           y += tHt;



           //Billing Statement

           cFont = new Font("Arial", 11f, FontStyle.Bold);
           e.Graphics.DrawString("Billing Statement ", cFont, Brushes.Black, lm + 5, y, sf);

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           e.Graphics.DrawString("Room Price ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           sf.Alignment = StringAlignment.Far;
           e.Graphics.DrawString("" + roomPrice.ToString("#,#0.00"), cFont, Brushes.Black, lm + 350, y, sf);

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           sf.Alignment = StringAlignment.Near;
           e.Graphics.DrawString("Additional Half Day Amount: ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           sf.Alignment = StringAlignment.Far;
           e.Graphics.DrawString("" + halfDay.ToString("#,#0.00"), cFont, Brushes.Black, lm + 350, y, sf);

           y += tHt;
           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           sf.Alignment = StringAlignment.Near;
           e.Graphics.DrawString("Room Accomodation Amount: ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           sf.Alignment = StringAlignment.Far;
           e.Graphics.DrawString("" + roomAmount.ToString("#,#0.00"), cFont, Brushes.Black, lm + 350, y, sf);

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           sf.Alignment = StringAlignment.Near;
           e.Graphics.DrawString("Additional Complimentary Breakfast: ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           sf.Alignment = StringAlignment.Far;
           e.Graphics.DrawString("" + txtExtraComplementary.Text, cFont, Brushes.Black, lm + 350, y, sf);

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           sf.Alignment = StringAlignment.Near;
           e.Graphics.DrawString("Additional Swimming Entrance: ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           sf.Alignment = StringAlignment.Far;
           e.Graphics.DrawString("" + txtExtraSwimming.Text, cFont, Brushes.Black, lm + 350, y, sf);

           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Regular);
           sf.Alignment = StringAlignment.Near;
           e.Graphics.DrawString("Discount Given: ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           sf.Alignment = StringAlignment.Far;
           e.Graphics.DrawString("" + txtDiscount.Text, cFont, Brushes.Black, lm + 350, y, sf);

           y += tHt;
           y += tHt;
           cFont = new Font("Arial", 11f, FontStyle.Bold);
           sf.Alignment = StringAlignment.Near;
           e.Graphics.DrawString("Grand Total: ", cFont, Brushes.Black, lm + 5, y, sf);
           cFont = new Font("Arial Narrow", 11f, FontStyle.Underline);
           sf.Alignment = StringAlignment.Far;
           e.Graphics.DrawString("" + txtGrandTotal.Text, cFont, Brushes.Black, lm + 350, y, sf);
           */
        }
        #endregion

        #region Common
        //Common
        private void UnityEvents()
        {
            proc.ProcessCompleted += new ProcessHandler(delegate(string id, string desc)
            {
                t.SafeCall(this, delegate
                {
                    float balAmt = 0f;
                    float grsAmt = 0f;
                    float payAmt = 0f;
                    float dscAmt = 0f;
                    try
                    {
                        switch (id)
                        {
                            case "SAVETRANSACTIONITEMS":
                                lstRegs.Items.Clear();

                                for (int i = 0; i < TransData.Count; i++)
                                {
                                    string strData = "", strDateTime = "";
                                    float regPrice = TransData[i].RegPrice;
                                    if (TransData[i].Details != null)
                                    {
                                        if (TransData[i].Details.Count == 1)
                                            strData = TransData[i].Details[0].StringData;
                                        else
                                            strData = TransData[i].Details[1].StringData;
                                    }

                                    strDateTime = TransData[i].RegDateTime.ToString("yyyy-MM-dd hh:mm:ss");

                                    lstRegs.Items.Add("Svc", string.Format("{0},{1},{2},Amt: {3}",
                                        strDateTime,
                                        TransData[i].RegType,
                                        strData,
                                        TransData[i].RegPrice.ToString("#,#0.00")),
                                        0
                                        );

                                    if (TransData[i].RegType.Equals("DISCOUNT_PERCENT"))
                                    {
                                        balAmt -= (grsAmt * (regPrice / 100f));
                                        dscAmt += (grsAmt * (regPrice / 100f));
                                    }
                                    else if (TransData[i].RegType.Equals("DISCOUNT_AMOUNT"))
                                    {
                                        balAmt -= regPrice;
                                        dscAmt += regPrice;
                                    }
                                    else if (TransData[i].RegType.Equals("PAYMENT"))
                                    {
                                        balAmt -= regPrice;
                                        payAmt += regPrice;
                                    }
                                    else
                                    {
                                        balAmt += regPrice;
                                        grsAmt += regPrice;
                                    }
                                }
                                lstRegs.Items.Add("Svc", string.Format("Total Amount : {0}",
                                               grsAmt.ToString("#,#0.00")),
                                               1
                                               );
                                lstRegs.Items.Add("Svc", string.Format("Payments Made : {0}",
                                               payAmt.ToString("#,#0.00")),
                                               1
                                               );
                                lstRegs.Items.Add("Svc", string.Format("Total Discounts : {0}",
                                               dscAmt.ToString("#,#0.00")),
                                               1
                                               );
                                lstRegs.Items.Add("Svc", string.Format("Balance : {0}",
                                                balAmt.ToString("#,#0.00")),
                                                1
                                                );
                                curTransData = new TransactionItemType();

                                lstServices.SelectedIndex = -1;
                                txtServicePrice.Value = 0.0m;
                                btnServiceDetails.Text = "No details";
                                chkServiceTime.Checked = false;

                                UnityScript[] dat;
                                UnityElement edat;
                                proc.DBPUX_Data_Fetch(out dat);
                                dat[0].Data_Get(0, out edat);
                                RegNum = "R" + int.Parse(edat.Data_GetField(0).ToString()).ToString("000000000");

                                txtRegNum_1.Text = RegNum;
                                txtRegNum_2.Text = RegNum;
                                txtRegNum_3.Text = RegNum;
                                txtRegNum_4.Text = RegNum;

                                //clear for payment tab
                                txtPaymentAmount.Value = 0.0m;
                                lstDetails.Items.Clear();
                                lstPayments.SelectedIndex = 0;
                                txtOR.Text = "";
                                break;
                            case "LOADDETAILS":
                                UnityScript[] udet;
                                UnityElement eldet;
                                proc.DBPUX_Data_Fetch(out udet);
                                udet[0].Data_Get(0, out eldet);
                                if (createNew)
                                {
                                    TransNum = "T" + int.Parse(eldet.Data_GetField(0).ToString()).ToString("000000000");
                                    txtTransNum.Text = TransNum;
                                }
                                udet[1].Data_Get(0, out eldet);
                                RegNum = "R" + int.Parse(eldet.Data_GetField(0).ToString()).ToString("000000000");


                                txtRegNum_1.Text = RegNum;
                                txtRegNum_2.Text = RegNum;
                                txtRegNum_3.Text = RegNum;
                                txtRegNum_4.Text = RegNum;

                                lstServices.Items.AddRange(udet[2].ToList<string>(0));
                                lstPackages.Items.AddRange(udet[3].ToList<string>(0));
                                lstPayments.Items.AddRange(udet[4].ToList<string>(0));
                                //clear content additional code
                                lstcats.Clear();
                                amCats.Clear();

                                autoRef.AddRange(udet[5].ToList<string>(0));
                                autoName.AddRange(udet[5].ToList<string>(1));
                                lstcats.AddRange(udet[6].ToList<string>(0));
                                amCats.AddRange(udet[8].ToList<string>(0));

                                lstDiscountMsg.Items.Clear();
                                lstDiscountMsg.Items.AddRange(udet[7].ToList(0));
                                txtCustName.AutoCompleteCustomSource.AddRange(autoName.ToArray());

                                TransState(true);
                                if (!createNew)
                                    btnAdd.Enabled = false;
                                //tabTransactions.Visible = true;

                                break;
                            case "CREATETRANS":
                                TransResetFields();
                                LoadTransactionList();
                                grpTransaction.Visible = false;
                                btnAdd.Enabled = true;
                                break;
                            case "LOADTRANSLIST":
                                UnityScript[] utl;
                                proc.DBPUX_Data_Fetch(out utl);
                                grdItems.DataSource = utl[0].ToDataTable();
                                for (int i = 0; i < grdItems.Columns.Count; i++)
                                {
                                    grdItems.Columns[i].Width = 180;
                                }
                                if (utl[0].Data_Count == 50)
                                    txtPage.Maximum = txtPage.Value + 1;
                                else
                                    txtPage.Maximum = txtPage.Value;

                                txtSearchResult.Text = utl[0].Data_Count + " Search result(s)";
                                MainState(true);
                                break;
                            case "LOADTRANSDATA":
                                UnityScript[] utd;
                                proc.DBPUX_Data_Fetch(out utd);
                                UnityElement el;
                                utd[0].Data_Get(0, out el);

                                grpTransaction.Visible = true;
                                txtTransNum.Text = el.Data_GetField(0).ToString();
                                txtRefNum.Text = el.Data_GetField(1).ToString();
                                txtCustName.Text = el.Data_GetField(2).ToString();
                                txtTransactionDate.Text = el.Data_GetField(3).ToString();

                                txtCustName.ReadOnly = true;
                                txtTransactionDate.Enabled = false;
                                tabTransactions.Visible = true;
                                //display 
                                lstRegs.Items.Clear();
                                DataTable tblItems = utd[1].ToDataTable();
                                DataTable tblItemDetails = utd[2].ToDataTable();

                                transactionInfo = new printModData[0];

                                for (int i = 0; i < tblItems.Rows.Count; i++)
                                {
                                    string fRegNum = tblItems.Rows[i]["fRegNum"].ToString();
                                    curTransData = new TransactionItemType();
                                    curTransData.Details = new List<TransactionItemDetailType>();
                                    for (int j = 0; j < tblItemDetails.Rows.Count; j++)
                                    {
                                        string ffRegNum = tblItemDetails.Rows[j]["fRegNum"].ToString();
                                        string strDateTime = "", strRegType = "", strData = "";
                                        float regPrice = 0.0f;

                                        bool det = tblItemDetails.Rows[j]["fKeyID"].ToString().Equals("TYPE") || tblItemDetails.Rows[j]["fKeyID"].ToString().Equals("NOTES");
                                        if (fRegNum.Equals(ffRegNum) && det)
                                        {
                                            strDateTime = tblItems.Rows[i]["fDateTime"].ToString();
                                            strRegType = tblItems.Rows[i]["fType"].ToString();
                                            strData = tblItemDetails.Rows[j]["fStringData"].ToString();
                                            regPrice = float.Parse(tblItems.Rows[i]["fPrice"].ToString());
                                            lstRegs.Items.Add("Svc", string.Format("{0},{1},{2},Amt: {3}",
                                                strDateTime,
                                                strRegType,
                                                strData,
                                                regPrice.ToString("#,#0.00")),
                                                0
                                                );
                                            //additional for the printing module
                                            Array.Resize<printModData>(ref transactionInfo, transactionInfo.Length + 1);
                                            transactionInfo[transactionInfo.Length - 1].strDateTime = strDateTime;
                                            transactionInfo[transactionInfo.Length - 1].strRegData = strData;
                                            transactionInfo[transactionInfo.Length - 1].strRegType = strRegType;
                                            transactionInfo[transactionInfo.Length - 1].regPrice = regPrice;


                                            curTransData.RegDateTime = DateTime.Parse(strDateTime);
                                            curTransData.RegType = strRegType;
                                            curTransData.RegPrice = regPrice;
                                            curTransData.Details.Add(new TransactionItemDetailType() { StringData = strData });
                                            TransData.Add(curTransData);

                                            if (tblItems.Rows[i]["fType"].ToString().Equals("DISCOUNT_PERCENT"))
                                            {
                                                balAmt -= (grsAmt * (regPrice / 100f));
                                                dscAmt += (grsAmt * (regPrice / 100f));
                                            }
                                            else if (tblItems.Rows[i]["fType"].ToString().Equals("DISCOUNT_AMOUNT"))
                                            {
                                                balAmt -= regPrice;
                                                dscAmt += regPrice;
                                            }
                                            else if (tblItems.Rows[i]["fType"].ToString().Equals("PAYMENT"))
                                            {
                                                balAmt -= regPrice;
                                                payAmt += regPrice;
                                            }
                                            else if (tblItemDetails.Rows[j]["fKeyID"].ToString().Equals("TYPE"))
                                            {
                                                balAmt += regPrice;
                                                grsAmt += regPrice;
                                            }
                                        }
                                    }
                                }
                                lstRegs.Items.Add("Svc", string.Format("Total Amount : {0}",
                                               grsAmt.ToString("#,#0.00")),
                                               1
                                               );
                                lstRegs.Items.Add("Svc", string.Format("Payments Made : {0}",
                                               payAmt.ToString("#,#0.00")),
                                               1
                                               );
                                lstRegs.Items.Add("Svc", string.Format("Total Discounts : {0}",
                                               dscAmt.ToString("#,#0.00")),
                                               1
                                               );
                                lstRegs.Items.Add("Svc", string.Format("Balance : {0}",
                                                balAmt.ToString("#,#0.00")),
                                                1
                                                );
                                InitTransactionWindow(false);
                                isViewing = false;
                                break;
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                });
            });
            proc.ProcessError += new ProcessHandler(delegate(string id, string desc)
            {
                t.SafeCall(this, delegate
                {
                    MessageBox.Show(desc);
                });
            });
        }
        private void RoundOffTime()
        {
            curTime = new TimeSpan(curTime.Hours, curTime.Minutes, 0);
            if (curTime.Minutes < 15)
            {
                curTime = new TimeSpan(curTime.Hours, 0, 0);
            }
            else if(curTime.Minutes > 15 && curTime.Minutes < 30)
            {
                curTime = new TimeSpan(curTime.Hours, 30, 0);
            }
            else if (curTime.Minutes > 30 && curTime.Minutes < 45)
            {
                curTime = new TimeSpan(curTime.Hours, 30, 0);
            }
            else if (curTime.Minutes > 45 && curTime.Minutes < 59)
            {
                curTime = new TimeSpan(curTime.Hours + 1, 0, 0);
            }
        }
        #endregion
    }
}

        